package com.china.produce.netty.learning.server;

import com.china.produce.netty.learning.protocol.MessageCodecSharable;
import com.china.produce.netty.learning.protocol.ProcotolFrameDecoder;
import com.china.produce.netty.learning.server.handler.ChatRequestMessageHandler;
import com.china.produce.netty.learning.server.handler.GroupChatRequestMessageHandler;
import com.china.produce.netty.learning.server.handler.GroupCreateRequestMessageHandler;
import com.china.produce.netty.learning.server.handler.LoginRequestMessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

/**
 *
 * 聊天server
 *
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/9/16
 */
public class ChatGroupServer {

    public static void main(String[] args) throws InterruptedException {
        //处理客户端连接，只负责接收连接，连接交给WorkerGroup处理
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("boss"));
        //处理具体IO事件
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(4, new DefaultThreadFactory("worker"));

        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();


        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                               @Override
                               protected void initChannel(NioSocketChannel ch) throws Exception {
                                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                                    ch.pipeline().addLast(LOGGING_HANDLER);
                                    ch.pipeline().addLast(MESSAGE_CODEC);
                                    //服务端判断读空闲时间大于30s, 30s内没有收到channel数据，会触发IdleState#READER_IDLE 事件
                                    ch.pipeline().addLast(new IdleStateHandler(30, 0, 0));
                                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                                        @Override
                                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                            if (evt instanceof IdleStateEvent) {
                                                IdleStateEvent event = (IdleStateEvent) evt;
                                                //触发读事件
                                                if (event.state() == IdleState.READER_IDLE) {
                                                    System.out.println("已经30s没有读到数据了!");
                                                    ctx.channel().close();
                                                }
                                            }
                                        }
                                    });
                                   ch.pipeline().addLast(LOGIN_HANDLER);
                                   ch.pipeline().addLast(CHAT_HANDLER);
                                   ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                                   ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                               }
                           });

            Channel channel = serverBootstrap.bind(8081).sync().channel();
            System.out.println("===netty服务器启动====");
            channel.closeFuture().sync();
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
